package org.jacp.demo.util;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

import org.im4java.process.ProcessEvent;
import org.im4java.process.ProcessEventListener;
import org.jacp.api.action.IAction;
import org.jacp.api.action.IActionListener;

/**
 * check each process, notify components when process started and ended
 * @author Andy Moncsek
 *
 */
public final class ProccessTerminationListener implements ProcessEventListener {
	private static final List<String> pid = new CopyOnWriteArrayList<String>();
	protected IActionListener<ActionListener, ActionEvent, Object> listener;
	
	public ProccessTerminationListener() {

	}
	
	public ProccessTerminationListener(final IActionListener<ActionListener, ActionEvent, Object> listener) {
		this.listener = listener;
	}
	
	

	// empty implementation
	public void processInitiated(final ProcessEvent pEvent) {
			if (pid.isEmpty()) {
				final IAction<ActionEvent, Object> myAction = listener.getAction();
				ActionListener myLstener = listener.getListener();
				myAction.addMessage("id02", "busy");
				myLstener.actionPerformed(myAction.getActionEvent());
			pid.add(pEvent.toString());
		}

	}
	
	public void processInitiated(final String file) {
			if (pid.isEmpty()) {
				final IAction<ActionEvent, Object> myAction = listener.getAction();
				ActionListener myLstener = listener.getListener();
				myAction.addMessage("id02", "busy");
				myLstener.actionPerformed(myAction.getActionEvent());
			}
			pid.add(file);

	}

	// save the started process
	public void processStarted(ProcessEvent pEvent) {

	}

	// print return-code or stack-trace
	public void processTerminated(final ProcessEvent pEvent) { //
			pid.remove(pEvent.toString());
			if (pid.isEmpty()) {
				final IAction<ActionEvent, Object> myAction = listener.getAction();
				ActionListener myLstener = listener.getListener();
				myAction.addMessage("id02", "stop");
				myLstener.actionPerformed(myAction.getActionEvent());
			}
	}
	
	// print return-code or stack-trace
	public void processTerminated(final String file) { //
			pid.remove(file);
			if (pid.isEmpty()) {
				final IAction<ActionEvent, Object> myAction = listener.getAction();
				ActionListener myLstener = listener.getListener();
				myAction.addMessage("id02", "stop");
				myLstener.actionPerformed(myAction.getActionEvent());
			}

	}

	// check if thread is still running
	public boolean isRunning() {
		return !pid.isEmpty();
	}

}
